/**
 * Created by ACER on 2017/4/3.
 */
app.controller("personal-profile-edit", function ($scope, $http) {
    var token = localStorage.getItem("token");


    //用户信息


    $scope.userInfo = {};

    $scope.userInfo.birthday = new Date();

    $scope.getInfo = function () {
        if (!token) {
            $.alert('请先登录', function () {
                location.href = '#login';
            });
            return;
        }

        $.showPreloader('正在获取中...');
        if (token) {
            $http({
                method: 'get',
                url: app.netPath + '/users/details/show',
                headers: {Authorization: token}
            }).then(function (res) {
                console.log(res);
                if (!res.data.error) {
                    $scope.userInfo = res.data.data;
                    $scope.userInfo.birthday = new Date($scope.userInfo.userBirthday);
                    //$scope.userInfo.userAvatarAddress = net + "/resources/img/" + res.data.data.userAvatar;
                    if ($scope.userInfo.userSex != null) {
                        $scope.userInfo.userSexWord = $scope.userInfo.userSex == 0 ? "男" : "女";
                    }
                    var avatarImg = {};

                    if (res.data.data.userAvatarAddress) {
                        avatarImg.imgAddress = app.netPath + '/resources/img/' + res.data.data.userAvatarAddress;
                        $scope.userInfo.avatarImg = avatarImg;
                    }

                    $.hidePreloader();
                }
                else {
                    $.alert("错误代码:" + res.data.error + "," + res.data.msg)
                    $.hidePreloader();
                }

            }, function () {
                $.alert('网络或设置错误！');
                $.hidePreloader();
            })
        }
    };


    //单次提交图片的函数
    //参数为传入的一个文件类型input
    $scope.img_upload = function (files) {

        console.log('ready to upload img.')

        if (!token) {
            return;
        }

        if (!files || !files[0]) {
            return;
        }

        //规定上传到服务器图片的大小
        var needHeight = 80;
        var needWidth = 80;

        //规定略缩图大小
        var smallWidth = needWidth * 0.33;

        //FileReader用来读取本地文件
        var reader = new FileReader();

        //实例化图片用于被加载在画布上
        var img = new Image();

        // 破除一个协议
        img.setAttribute("crossOrigin", 'Anonymous');

        //声明一个画布对象，当图片上传成功后添加到数组中便于显示
        var img_obj = {};

        //获取当前时间戳作为画布唯一id
        img_obj.id = new Date().getTime();

        //自动刷新双向绑定，预防双向绑定失效
        $scope.$digest();

        //获取预览画布
        var canvas = document.createElement('canvas');
        canvas.width = needWidth;
        canvas.height = needHeight;


        //控制略缩图大小
        canvas.style.width = smallWidth + 'px';

        var ctx = canvas.getContext("2d");

        //当图片加载完毕执行动作
        reader.onload = function () {

            // 通过 reader.result 来访问生成的 DataURL
            img.src = reader.result;

            img.onload = function () {

                //获取图片的高宽
                var width = img.width;
                var height = img.height;

                //获取需要使用的矩形图片区域
                var real_width = width * needHeight / needWidth > height ? height * needWidth / needHeight : width;
                var real_height = width > height * needWidth / needHeight ? height : width * needHeight / needWidth;

                //console.log('need:'+real_width+' '+real_height);
                //console.log('real:'+width+' '+height);

                //定位使图片居中
                var img_x = (width - real_width) / 2;
                var img_y = (height - real_height) / 2;

                //在画布上渲染头像预览
                ctx.drawImage(img, img_x, img_y, real_width, real_height, 0, 0, needWidth, needHeight);

                //将画布渲染的图像转换为base64字符串储存在data中
                var data = canvas.toDataURL();

                //发送POST请求
                $http({

                    method: 'post',
                    url: app.netPath + "/users/details/image-upload",
                    headers: {'Authorization': token},
                    data: data

                }).then(function (res) {

                    if (!res.data.error) {

                        //将获得的图片名暂时保存
                        img_obj.imgName = res.data.data;

                        //将获取图片名转换为路径用以显示
                        img_obj.imgAddress = app.netPath + '/resources/img/' + img_obj.imgName;

                        $scope.userInfo.avatarImg = img_obj;
                    } else {
                        $.alert('错误代码：' + res.data.error + "," + res.data.msg);
                    }


                }, function () {
                    $scope.img_del(index);
                    $.alert('网络或设置错误');
                });
                //清除原来画布内容
                ctx.clearRect(0, 0, needWidth, needHeight);
            };


        };


        //加载选中的图片
        reader.readAsDataURL(files[0]);
    };


    $scope.editInfo = function () {
        if (token) {
            if ($scope.userInfo.avatarImg.imgName) {
                $scope.userInfo.userAvatarAddress = $scope.userInfo.avatarImg.imgName;
            }
            $scope.userInfo.userSex = $scope.userInfo.userSexWord == "男" ? 0 : 1;
            $scope.userInfo.userBirthday = $scope.userInfo.birthday.getTime();

            console.log($scope.userInfo);
            //发送POST请求
            $http({
                method: 'post',
                url: app.netPath + '/users/details/revise',
                headers: {Authorization: token},
                data: $scope.userInfo
            }).then(function (res) {
                console.log(res);
                if (!res.data.error) {

                    $.alert(res.data.msg, function () {
                        //刷新用户信息
                        $scope.getInfo();
                        $.hidePreloader();
                    });

                } else {
                    $.alert('错误代码：' + res.data.error + "," + res.data.msg);
                    $.hidePreloader();
                }
            }, function () {
                $.alert('网络或设置错误');
                $.hidePreloader();
            })
        }
    };

    $scope.logout = function () {
        if (token) {
            localStorage.removeItem("token");
            $.alert("您已注销成功");
            location.href = '#home';

        }

    }


});